package com.th.cash.th2.login

import android.text.TextUtils
import androidx.lifecycle.viewModelScope
import com.th.basemodel.base.BaseViewModel
import com.th.basemodel.ext.toast
import com.th.basemodel.utils.AppUtil
import com.th.cash.storage.LocalSetting
import com.th.cash.th2.main.MainState
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch


class LoginVm : BaseViewModel() {

    private val repository by lazy{
        LoginRepository()
    }

    val intentChannel = Channel<LoginIntent>(Channel.UNLIMITED)

    //可变状态数据流（读写）（StateFlow替代LiveData，难道每一个页面都需要定义一个）
    private val _uiState = MutableStateFlow<LoginState>(LoginState.Idle)

    //可观察状态数据流（只读）
    val uiState: StateFlow<LoginState> get() = _uiState

    init {
        viewModelScope.launch {

            intentChannel.consumeAsFlow().debounce(500).collect { value ->
                when (value) {
                    is LoginIntent.SendSms -> {
                        sendSms(value.request)
                    }
                    is LoginIntent.Login -> {
                        login(value.request)
                    }
                    else ->{

                    }
                }
            }
        }
    }

    private fun sendSms(request: SendSmsRequest) {
        if (TextUtils.isEmpty(request.fqNHWPuQuerulouslyXUxeOCr)) {
            toast("กรุณากรอกหมายเลขโทรศัพท์มือถือ")
            return
        }

        _uiState.value = LoginState.Idle

        viewModelScope.launch {
            loadStartLoading()

            val result = repository.sendSms(request)

            result.checkResult(success = {
                loadSuccess()
                _uiState.value = LoginState.SendSmsSuccess(it?.apply {
                    phone = request.fqNHWPuQuerulouslyXUxeOCr
                })
            }, error = {
                loadError(it)
            })
        }
    }

    private fun login(request: LoginRequest) {
        _uiState.value = LoginState.Idle

        viewModelScope.launch {
            loadStartLoading()

            val result = repository.login(request)

            result.checkResult(success = {
                loadSuccess()
                // 处理登录成功后的逻辑

                it?.run {
                    LocalSetting.userAdult = MRZamUjLamppostNaUomFq.EipjCjOWampusTxPKtZv
                    LocalSetting.userSession = MRZamUjLamppostNaUomFq.QZiwXqeTurncoatTpebxhu
                    LocalSetting.userPhone = request.gKnNaCnAdmissibilityVxnWLrH
                    LocalSetting.userLogin = true
                    LocalSetting.lastLoginTime = System.currentTimeMillis()

                    AppUtil.sessionId = LocalSetting.userSession
                    AppUtil.userPhone = LocalSetting.userPhone

                    _uiState.value = LoginState.VerifyResult(true)

                }
            }, error = {
                loadError(it)
                _uiState.value = LoginState.VerifyResult(false)
            })
        }
    }

}